<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ################

class JFX_Module_Jfxmenu extends JFX_Module {

    public $keyname = 'jfxmenu';
    public $title = 'JFX Menu';
    public $version = '0.2.3';
    public $dependencies = array(

    );

    public function __construct(){
        parent::__construct();

    }

    public function getBlockActions(){
        return array(
            array(
                'keyname' => 'menu',
                'title' => 'Insert Menu',
                'description' => ''
            )
        );
    }

    public function copyToNewBlock($oldid, $newid, $oldworkspaceid, $newworkspaceid){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        //$DB->showOutput(true);
        //$DB->showErrors(true);
        $tplid = $DB->oneValue($CONFIG->dbprefix.'jfxmenu_blocks_to_menus', 'menu_key', "block_id = '{$oldid}'");
        $dbParams = array(
            'block_id' => $newid,
            'menu_key' => $tplid
        );
        $DB->insert($CONFIG->dbprefix.'jfxmenu_blocks_to_menus', $dbParams);
        //$DB->showOutput(false);
        //$DB->showErrors(false);
    }

    public function updateSettings($params){

        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');

        $mData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}jfxmenu_blocks_to_menus WHERE block_id = '{$params['id']}'");
        if(!is_array($mData)) $defaultMenu = $DB->oneValue($CONFIG->dbprefix.'jfxmenu_menus', 'keyname', '1');
        else $defaultMenu = $mData['keyname'];

        if(Antz_IntelliForm::submitted('select-menu')){
            $error = false;
            $menu = preg_replace('/[^a-zA-Z0-9]/', '', post('menu'));
            if($DB->countRows($CONFIG->dbprefix.'jfxmenu_menus', "keyname = '{$menu}'")==0){
                $error = true;
                JFX::addError($this->lang('invalid_menu'));
            }
            if(!$error){
                $dbParams = array(
                    'block_id' => $params['id'],
                    'menu_key' => $menu
                );
                if($DB->countRows($CONFIG->dbprefix.'jfxmenu_blocks_to_menus', "block_id = '{$params['id']}' AND menu_key = '{$menu}'")==0){
                    // insert
                    $DB->insert($CONFIG->dbprefix.'jfxmenu_blocks_to_menus', $dbParams);
                }else{
                    // update
                    $DB->update($CONFIG->dbprefix.'jfxmenu_blocks_to_menus', $dbParams, "block_id = '{$params['id']}' AND menu_key = '{$menu}'");
                }
                JFX::addSuccess($this->lang('success'));
            }
        }


        $menuOpts = array();
        $menus = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}jfxmenu_menus ORDER BY keyname ASC");
        foreach($menus as $k=>$v){
            $menuOpts[$v['keyname']] = $this->getContentLang('title', $v['keyname']);
        }
        $formFields = array(
            array(
                'type' => 'select',
                'name' => 'menu',
                'value' => post('menu', $defaultMenu),
                'options' => $menuOpts,
                'label' => $this->lang('menu')
            ),
            array(
                'type' => 'submit',
                'name' => 'submitBtn',
                'value' => $this->lang('submit'),
                'label' => '&nbsp;'
            )
        );
        echo JFX::makeRapidForm($formFields, $this->lang('select_menu'), 'select-menu');
    }


    public function getContent($params){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');

        $menuType = $DB->oneValue($CONFIG->dbprefix.'jfxmenu_blocks_to_menus', 'menu_key', "block_id = '{$params['id']}'");

        $mData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}jfxmenu_menus WHERE keyname = '{$menuType}'");

        return $this->fetchMenu($mData['parent_id'], $mData['template']);


    }

    public function prepare($details){
        return $this->getContent($details);
    }
    
    public function fetchMenu($parentid, $template){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');

        $pData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}pages WHERE id = '{$parentid}'");

        if(!is_array($pData)) return;

        $pData['subpages'] = JFX::getPageTree($parentid, $USER->workspace);
        $pData = $this->checkMenuPermissions($pData);

        $template = str_replace('{$subpages}', ':|subpages|:', $template);

        $subpages = '';
        $subpagesCount = count($pData['subpages']);
        foreach($pData['subpages'] as $k=>$v){
            $v['is_first'] = false;
            $v['is_last'] = false;
            if($k == $subpagesCount-1) $v['is_last'] = true;
            if($k==0) $v['is_first'] = true;
            $subpages .= $this->fetchIntoTemplate($v, $template);
        }

        return $subpages;

    }

    public function checkMenuPermissions($pageTree){
        foreach($pageTree['subpages'] as $k=>$v){
            $params = array(
                'page_id' => $v['id'],
                'allowed' => true
            );
            JFX::hook('JFX_Module_Menu.showMenu', $params);
            if(!$params['allowed']){
                unset($pageTree['subpages'][$k]);
                continue;
            }
            if(count($v['subpages'])>0){
                $pageTree['subpages'][$k] = $this->checkMenuPermissions($v);
            }
        }
        $pageTree['subpages'] = array_regenerate_keys($pageTree['subpages']);
        return $pageTree;
    }

    public function fetchIntoTemplate($pageTree, $template){
        $LANG = JFX::registry('lang');
        $SMARTY = JFX::registry('Smarty');
        $LINK = JFX::registry('JFX_Link');

        $currentPageid = $LINK->getPageId();

        if(is_array($pageTree['subpages'])){
            $subpages = '';
            $subpagesCount = count($pageTree['subpages']);
            foreach($pageTree['subpages'] as $k=>$v){
                $v['is_first'] = false;
                $v['is_last'] = false;
                if($k == $subpagesCount-1) $v['is_last'] = true;
                if($k==0) $v['is_first'] = true;
      
                $subpages .= $this->fetchIntoTemplate($v, $template);
            }
            
        }else{
            $subpages = '';
        }
        
        $pageTree['num_sub_pages'] = count($pageTree['subpages']);

        $parentids = array();
        JFX::getParentIdsAsArray($currentPageid, $parentids);

        if($currentPageid == $pageTree['id']){
            $pageTree['is_current'] = true;
        }else{
            $pageTree['is_current'] = false;
            if(in_array($pageTree['id'], $parentids)){
                $pageTree['is_selected_parent'] = true;
            }else{
                $pageTree['is_selected_parent'] = false;
            }
        }

        $pageTree['title'] = $LANG->getContent('core', 'page_menu', $pageTree['id']);
        $pageTree['url'] = JFX::getUrlById($pageTree['id']);
        

        $SMARTY->assign('node', $pageTree);
        $SMARTY->_compile_source('JFX_Module_Jfxmenu::fetchIntoTemplate', $template, $_compiled);
        ob_start();
        $SMARTY->_eval('?>' . $_compiled);
        $template = ob_get_contents();
        ob_end_clean();
        $template = str_replace(':|subpages|:', $subpages, $template);
        
        return $template;
    }

    public function admin($url, $dirname){

        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $SMARTY->assign('actionUrl', $url);
        $LANG = JFX::registry('lang');

        $this->addStylesheet('admin.css');

        $tabs = array(
            array(
                'keyname' => 'list',
                'title' => 'List Menus',
                'url' => $url.'/list'
            )
        );

        // find our selected tab
        $urlParts = explode('?', $_SERVER['REQUEST_URI']);
        $urlParts = explode('/', $urlParts[0]);
        foreach($urlParts as $k=>$v){
            if($v == $this->keyname) break;
        }
        $selectedTab = (array_key_exists($k+1, $urlParts))
            ? $urlParts[$k+1]
            : ''
            ;

        if($selectedTab == ''){
            $selectedTab = 'list';
        }

        foreach($tabs as $k=>$tab){
            if($selectedTab == $tab['keyname']){
                $tabs[$k]['class_name'] = 'selected';
            }
        }

        //include('admin-actions/tabs.php');

        $selectedTab = str_replace('../', '/', $selectedTab);

        echo '<div id="cst-admin-tab-content"><div id="cst-admin-tab-content-inner">';
            if(file_exists($dirname.'/admin-actions/'.$selectedTab.'.php')) include('admin-actions/'.$selectedTab.'.php');
            else echo $selectedTab.'.php does not exists';
        echo '</div></div>';

        
    }


    public function install(){
        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $dirname = str_replace(DIRECTORY_SEPARATOR, '/', dirname(__FILE__)).'/install';
        include('install/install.php');
    }


    public function uninstall(){
        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $dirname = str_replace(DIRECTORY_SEPARATOR, '/', dirname(__FILE__)).'/install';
        include('install/uninstall.php');
    }




}